package com.aluvfy.jdbc;

import com.aluvfy.jdbc.utils.DbUtils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/*使用PreparedStatement将表中的图片查询出来*/
public class JDBCTest16 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DbUtils.getConnection();
            String sql = "select img from t_img where name = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "img1");
            rs = ps.executeQuery();
            while (rs.next()) {
                //图片就在结果集ResultSet中
                //输入流
                InputStream in = rs.getBinaryStream("img");
                //输出流
                OutputStream out = new FileOutputStream("D:\\C_Photo\\BIZ\\img1.jpg");
                byte[] buffer = new byte[1024];
                int readCount = 0;
                while ((readCount = in.read(buffer)) != -1) {
                    out.write(buffer, 0, readCount);
                }
                out.flush();
                out.close();
                in.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.close(conn, ps, rs);
        }
    }
}
